package io.renren.modules.webofthing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.webofthing.dao.IotUserDao;
import io.renren.modules.webofthing.entity.IotUserEntity;
import io.renren.modules.webofthing.service.IotUserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;


@Service("iotUserService")
public class IotUserServiceImpl extends ServiceImpl<IotUserDao, IotUserEntity> implements IotUserService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String username = (String) params.get("username");
        Long userId = (Long) params.get("userId");
        IPage<IotUserEntity> page = this.page(
                new Query<IotUserEntity>().getPage(params),
                new QueryWrapper<IotUserEntity>().like(StringUtils.isNotBlank(username), "user_name", username)
                        .eq(userId != null, "user_id", userId)
        );
        return new PageUtils(page);
    }

    @Override
    public boolean saveIotUserEntity(IotUserEntity iotUser) {
        Date birthday = iotUser.getBirthday();
        int age = 0;
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        iotUser.setPassword(new Sha256Hash(iotUser.getPassword(), salt).toHex());
        iotUser.setSalt(salt);
        try {
            age = DateUtils.getAge(birthday);
        } catch (Exception e) {
            e.printStackTrace();
        }
        iotUser.setAge(age);
        int insert = this.baseMapper.insert(iotUser);
        //添加用户成功
        return insert > 0;
        //添加用户失败
    }

}